package com.example.service.impl;

import com.example.dao.CartDao;
import com.example.entity.Cart;
import com.example.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

	@Autowired
	private CartDao cartDao;

	@Override
	public List<Cart> listCart(Cart cart) {
		return cartDao.listCart(cart);
	}

	@Override
	public int saveCart(Cart cart) {
		Cart existCart = cartDao.getCart(cart.getShopId(), cart.getUserId(), cart.getFoodId());
		if (existCart == null) {
			cart.setQuantity(1);
			return cartDao.saveCart(cart);
		} else {
			existCart.setQuantity(existCart.getQuantity() + 1);
			return cartDao.updateCart(existCart);
		}
	}

	@Override
	public int removeCart(Cart cart) {
		Cart existCart = cartDao.getCart(cart.getShopId(), cart.getUserId(), cart.getFoodId());
		if (existCart == null) {
			return 0;
		}
		existCart.setQuantity(existCart.getQuantity() - 1);
		if (existCart.getQuantity() <= 0) {
			return cartDao.removeCart(cart);
		} else {
			return cartDao.updateCart(existCart);
		}
	}
}